package com.github.ghsea.framework.job.client;

import java.util.List;

import org.apache.curator.utils.ZKPaths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.github.ghsea.framework.job.common.EndpointZkNodeData;
import com.github.ghsea.framework.job.common.JobApp;
import com.github.ghsea.framework.job.common.TriggerMetadata;
import com.github.ghsea.framework.job.common.exception.JobRegistryException;
import com.github.ghsea.framework.job.common.support.IpUtils;
import com.github.ghsea.framework.job.common.support.ZkPath;
import com.github.ghsea.framework.zkclient.ZkClient;

public class JobAppFactoryBean implements InitializingBean, DisposableBean, ApplicationListener<ContextRefreshedEvent> {

	private JobApp jobApp;

	private String zkServers;

	//TODO 重构
	private static ZkClient zkClient;

	private Logger log = LoggerFactory.getLogger(JobAppFactoryBean.class);

	public void onApplicationEvent(ContextRefreshedEvent event) {
		try {
			registerClientToZK();
			registerJobAppToServer();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
	}

	private void registerClientToZK() throws Exception {
		String zkServerPath = ZkPath.getPathOfClients();
		if (!zkClient.exist(zkServerPath)) {
			zkClient.create(zkServerPath);
		}

		String ipAndPort = IpUtils.getLocalIp() + ":" + jobApp.getPort();
		String serverZkPath = ZKPaths.makePath(ZkPath.getPathOfClients(), jobApp.getAuthorityInfo().getAppName(),
				ipAndPort);
		EndpointZkNodeData nodeData = new EndpointZkNodeData();
		nodeData.setBaseAccessUrl(jobApp.getBaseAccessUrl());
		if (zkClient.exist(serverZkPath)) {
			zkClient.delete(serverZkPath);
		}
		zkClient.createEphemeral(serverZkPath, nodeData, true);
	}

	private void registerJobAppToServer() throws JobRegistryException {
		JobRegistryClient jobRegistry = new JobRegistryClient(new JobServerLocator(zkClient));
		List<TriggerMetadata> triggers = jobApp.getTriggers();
		triggers.forEach(each -> {
			try {
				each.setAppName(jobApp.getAuthorityInfo().getAppName());
				jobRegistry.register(jobApp.getAuthorityInfo(), each);
			} catch (JobRegistryException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		});

	}

	public void afterPropertiesSet() throws Exception {
		zkClient = ZkClient.getInstance(zkServers);
	}

	@Override
	public void destroy() throws Exception {
		zkClient.close();
	}

	public void setJobApp(JobApp jobApp) {
		this.jobApp = jobApp;
	}

	public void setZkServers(String zkServers) {
		this.zkServers = zkServers;
	}

	public static ZkClient getZkClient() {
		return zkClient;
	}
	
	

}
